import { message } from '@/components/XtxUI'
import type { CartItem, CartList } from '@/types'
import { http } from '@/utils/request'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useMemberStore } from '..'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref<CartList>([])

    // 登录状态
    const isMemberLogin = computed(() => {
      const memberStore = useMemberStore()
      return memberStore.isLogin
    })

    // 有效商品列表，是否已下架或者有无库存
    const effectiveCartList = computed(() =>
      cartList.value.filter((item) => item.isEffective && item.stock > 0)
    )

    // 有效商品总数量
    const effectiveCartCount = computed(() =>
      effectiveCartList.value.reduce((sum, item) => sum + item.count, 0)
    )

    // 有效商品总价格(保留两位小数)
    const effectiveCartPrice = computed(() =>
      effectiveCartList.value
        .reduce((sum, item) => sum + Number(item.nowPrice) * item.count, 0)
        .toFixed(2)
    )

    // 购物车全选状态
    const isAllSelected = computed(
      () =>
        effectiveCartList.value.length > 0 && effectiveCartList.value.every((item) => item.selected)
    )

    // 已选择的商品列表
    const selectedCartList = computed(() => effectiveCartList.value.filter((item) => item.selected))

    // 已选择的商品总数量
    const selectedCartCount = computed(() =>
      selectedCartList.value.reduce((sum, item) => sum + item.count, 0)
    )

    // 已选择的商品总价格(保留两位小数)
    const selectedCartPrice = computed(() =>
      selectedCartList.value
        .reduce((sum, item) => sum + Number(item.nowPrice) * item.count, 0)
        .toFixed(2)
    )

    // 加入购物车
    const addCart = async (data: CartItem) => {
      const { skuId, count } = data
      if (isMemberLogin.value) {
        await http('POST', '/member/cart', { skuId, count })
        // 获取最新购物车列表
        getCartList()
      } else {
        const cartItem = cartList.value.find((item) => item.skuId === skuId)
        if (cartItem) {
          // 存在则数量相累加
          cartItem.count += count
        } else {
          // 不存在则添加到数组最前面
          cartList.value.unshift(data)
        }
      }
      message({ type: 'success', text: '加入购物车成功' })
    }

    // 获取购物车列表
    const getCartList = async () => {
      if (isMemberLogin.value) {
        const res = await http<CartList>('GET', '/member/cart')
        cartList.value = res.data.result
      } else {
        // 本地存储的库存信息和价格不是服务器最新的，所以需要主动获取最新商品信息
        cartList.value.forEach(async (item) => {
          const res = await http<CartItem>('GET', `/goods/stock/${item.skuId}`)
          const { isEffective, stock, nowPrice } = res.data.result
          // 更新商品是否有效
          item.isEffective = isEffective
          // 更新商品库存
          item.stock = stock
          // 更新商品现价
          item.nowPrice = nowPrice
        })
      }
    }

    // 删除购物车商品
    const deleteCart = async (data: { ids: string[] }) => {
      if (isMemberLogin.value) {
        const res = await http('DELETE', '/member/cart', data)
        if (res.data.result) {
          message({ type: 'success', text: '删除成功' })
          // 获取最新购物车列表
          getCartList()
        } else {
          message({ type: 'warn', text: '删除失败' })
        }
      } else {
        cartList.value = cartList.value.filter((item) => !data.ids.includes(item.skuId))
        message({ type: 'success', text: '删除成功' })
      }
    }

    // 修改购物车商品状态(是否选中，商品数量)
    const updateCart = async (skuId: string, data: { selected?: boolean; count?: number }) => {
      if (isMemberLogin.value) {
        await http('PUT', `/member/cart/${skuId}`, data)
        // 获取最新购物车列表
        getCartList()
      } else {
        const cartItem = cartList.value.find((item) => item.skuId === skuId)
        if (cartItem) {
          const { selected, count } = data
          if (selected !== undefined) cartItem.selected = selected
          if (count !== undefined) cartItem.count = count
        }
      }
    }

    // 修改购物车全选和反选状态
    // ids参数如果不传，表示用户访问的是全选和取消全选操作，后端根据selected确定用户是全选和取消全选
    const updateCartAllSelected = async (data: { selected: boolean; ids?: string[] }) => {
      if (isMemberLogin.value) {
        await http('PUT', '/member/cart/selected', data)
        // 获取最新购物车列表
        getCartList()
      } else {
        const { selected } = data
        cartList.value.forEach((item) => {
          item.selected = selected
        })
      }
      message({ type: 'success', text: '修改成功' })
    }

    // 退出登录清空购物车
    const clearCart = () => {
      cartList.value = [] as CartList
    }

    // 合并本地购物车
    const mergeLocalCart = async () => {
      const data = cartList.value.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count
      }))
      await http('POST', '/member/cart/merge', data)
      // 获取最新购物车列表
      getCartList()
    }

    return {
      cartList,
      isMemberLogin,
      effectiveCartList,
      effectiveCartCount,
      effectiveCartPrice,
      isAllSelected,
      selectedCartList,
      selectedCartCount,
      selectedCartPrice,
      addCart,
      getCartList,
      deleteCart,
      updateCart,
      updateCartAllSelected,
      clearCart,
      mergeLocalCart
    }
  },
  {
    persist: {
      key: 'rabbit-mall-cart'
    }
  }
)
